package com.gt.web.srv.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gt.web.api.exception.BusinessException;
import com.gt.web.srv.domain.SsActivity;
import com.gt.web.srv.mapper.SsActivityMapper;
import com.gt.web.srv.mapstructs.SsActivityStruct;
import com.gt.web.srv.service.SsActivityService;
import com.gt.web.srv.web.api.command.SsActivityCommand;
import com.gt.web.srv.web.api.resource.ss.SsActivityResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>describe</p >
 *
 * @author shenhuiyang
 * @version 1.0
 * @date 2025/5/29 18:52
 * @menu describe
 */
@Service
public class SsActivityServiceImpl implements SsActivityService {

    @Autowired
    private SsActivityMapper ssActivityMapper;

    @Override
    public SsActivityResource getById(Long ssParticipantsId) {
        return SsActivityStruct.INSTANCE.simple(ssActivityMapper.selectById(ssParticipantsId));
    }

    @Override
    public PageInfo<SsActivityResource> page(SsActivityCommand request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<SsActivity> list = ssActivityMapper.selectList(SsActivityStruct.INSTANCE.simple(request));
        List<SsActivityResource> repairApplicationResources = SsActivityStruct.INSTANCE.simpleList(list);
        return new PageInfo<>(repairApplicationResources);
    }

    @Override
    public void save(SsActivityCommand dto) {
        SsActivity ssActivity = SsActivityStruct.INSTANCE.simple(dto);
        if (dto.getActivityId() == null) {
            // 新增
            ssActivityMapper.insert(ssActivity);
        } else {
            // 更新
            ssActivityMapper.update(ssActivity);
        }
    }

    @Override
    public boolean updateStatus(Long activityGroupId, Integer status) {
        return ssActivityMapper.updateStatus(activityGroupId, status,null) > 0;
    }

    @Override
    public Boolean increaseEnrollNum(Long activityId, Integer num) {
        if (num <= 0) {
            throw new BusinessException(2000,"人数必须大于0");
        }
        SsActivity ssActivity = ssActivityMapper.selectById(activityId);
        if (ssActivity == null ) {
            throw new BusinessException(2001,"活动不存在");
        }
        if (ssActivity.getMaxPeopleNum() != null && ssActivity.getEnrollPeopleNum() != null &&
                ssActivity.getEnrollPeopleNum() + num > ssActivity.getMaxPeopleNum()) {
            throw new BusinessException(2002,"活动人数已满");
        }
        boolean b = ssActivityMapper.increaseEnrollNum(activityId, num) > 0;
        if (ssActivity.getEnrollPeopleNum() + num == ssActivity.getMaxPeopleNum()){
            ssActivityMapper.updateStatus(activityId, 2,null);
        }
        return  b;
    }
}
